package com.txsj.scan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.GoodsInfoDao;
import com.txsj.scan.R;
import com.txsj.scan.adapter.AllocationAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.presenter.AllocationPresenter;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.view.AllocationIView;
import com.txsj.scan.widget.dialog.CustomDialog;
import com.txsj.scan.widget.swipemenu.SwipeRecyView;

import java.text.DecimalFormat;
import java.util.List;


/**
 * 调拨单页面
 */
public class AllocationActivity extends BaseActivity<AllocationPresenter> implements AllocationIView, View.OnClickListener {

    public static final int OUT_INVENTORY = 0x175;
    public static final int IN_INVENTORY = 0x176;

    private TextView tv_out_name, tv_in_name, tv_allocation_count, tv_start;
    private EditText et_remarks;
    private XRefreshView xRefreshView;
    private SwipeRecyView content_recyclerView;
    private AllocationAdapter adapter;
    private RelativeLayout lay_in;

    private List<GoodsInfo> epcGoodsInfos;
    private WarehouseBean inWarehouseBean;
    private int allCount;
    private WarehouseBean warehouseBean;

    int systemCount;//系统库存数量，本地扫描到的数量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_allocation);
        initView();
        initData();
    }

    private void initData() {
        String jsonaArray0 = getIntent().getStringExtra("warehouse");
        warehouseBean = new Gson().fromJson(jsonaArray0,WarehouseBean.class);
        if (null != warehouseBean && !TextUtils.isEmpty(warehouseBean.getWarehouse_name())) {
            tv_out_name.setText(warehouseBean.getWarehouse_name());
        }
        String jsonaArray = getIntent().getStringExtra("data");
        if (TextUtils.isEmpty(jsonaArray)){
            return;
        }
        List<GoodsInfo> usefulGoodsEpcList = GsonFactory.getObjectList(jsonaArray,GoodsInfo.class);
        if (null != usefulGoodsEpcList && usefulGoodsEpcList.size() > 0) {
            epcGoodsInfos = usefulGoodsEpcList;
            adapter.setData(epcGoodsInfos);
        }

        for (GoodsInfo epcGoodsInfo:epcGoodsInfos){
            allCount+=epcGoodsInfo.getEpcList().size();
        }
        tv_allocation_count.setText(allCount+"");


        List<GoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder().
                where(GoodsInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                .list();
        systemCount = 0;//系统商品数量
        for (GoodsInfo goodsInfo:list){
            for (GoodsInfo epcGoodsInfo :adapter.getList()){
                if (goodsInfo.getGoods_id() == epcGoodsInfo.getGoods_id()){
                    systemCount += goodsInfo.getInventory_keep();
                }
            }
        }
    }

    /**
     * 在进行提交盘存的时候判断提交的数量<系统库存数量的时候提示文字
     * @return
     */
    private int getCommitListCount() {
        int count = 0;
        for (GoodsInfo info:adapter.getList()){
            count += info.getEpcList().size();
        }
        return count;
    }

    private void initView() {
        mTitle = findViewById(R.id.mTitle);
        tv_out_name = (TextView) findViewById(R.id.tv_out_name);
        lay_in = (RelativeLayout) findViewById(R.id.lay_in);
        tv_in_name = (TextView) findViewById(R.id.tv_in_name);
        tv_start = (TextView) findViewById(R.id.tv_start);
        tv_allocation_count = (TextView) findViewById(R.id.tv_allocation_count);
        et_remarks = (EditText) findViewById(R.id.et_remarks);
        xRefreshView = (XRefreshView) findViewById(R.id.xRefreshView);
        content_recyclerView = (SwipeRecyView) findViewById(R.id.content_recyclerView);
        lay_in.setOnClickListener(this);
        tv_start.setOnClickListener(this);
        //设置是否可以下拉刷新
        xRefreshView.setPullRefreshEnable(false);
        // 设置是否可以上拉加载
        xRefreshView.setPullLoadEnable(false);

        adapter = new AllocationAdapter(this);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        content_recyclerView.setLayoutManager(manager);
        content_recyclerView.setAdapter(adapter);
        adapter.setListener(new AllocationAdapter.OnItemClickListener() {
            @Override
            public void onDelete(int position) {
                //删除本地商品
                epcGoodsInfos.remove(position);
                adapter.removeData(position);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lay_in:
                Intent intent2 = new Intent(AllocationActivity.this,SelectWarehouseActivity.class);
                startActivityForResult(intent2,IN_INVENTORY);
                break;
            case R.id.tv_start:
                final CustomDialog dialog = new CustomDialog(AllocationActivity.this);
                if (getCommitListCount() > systemCount) {
                    dialog.setTitleStr("调拨提示!");
                    String steTip = "调拨数量（" + getCommitListCount() + "）大于当前仓库可用\n" +
                            "标签数量（" + systemCount + "），调拨完成后会出现系统库存为负的情况，是否确认提交？";
                    dialog.setContent(steTip);
                }else {
                    dialog.setContent("是否确认提交？");
                }
                dialog.setCancelVisiable();
                dialog.setOkVisiable(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            if (isRepeatClick())return;
                        gotoCommit();
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    /**
     * 提交调拨
     */
    private void gotoCommit() {
        if (null == warehouseBean){
            showErrorMsg("请选择入库仓库");
            return;
        }
        if (null == inWarehouseBean){
            showErrorMsg("请选择出库仓库");
            return;
        }
        if (inWarehouseBean.getWarehouse_id() == warehouseBean.getWarehouse_id()){
            showErrorMsg("入库仓库和出库仓库不能相同");
            return;
        }
        if (epcGoodsInfos.size() <= 0){
            showErrorMsg("调拨数量不能小于0");
            return;
        }
        String remakes = et_remarks.getText().toString();
//        if (TextUtils.isEmpty(remakes)){
//            showErrorMsg("备注不能为空");
//            return;
//        }
        presenter.commitGoods(warehouseBean,inWarehouseBean,epcGoodsInfos,remakes);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data || TextUtils.isEmpty(data.getStringExtra("result"))){
            return;
        }
        String json = (String) data.getSerializableExtra("result");
        WarehouseBean bean = new Gson().fromJson(json, WarehouseBean.class);
        if (requestCode == IN_INVENTORY) {
            inWarehouseBean = bean;
            tv_in_name.setText(inWarehouseBean.getWarehouse_name());
        }
    }

    @Override
    protected AllocationPresenter providePresenter() {
        return presenter = new AllocationPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }

    @Override
    public void onSuccess(String data) {
        hideLoading();
        showErrorMsg(data);
        Intent intent = new Intent(this, SelectGoodsListActivity.class);
//        intent.putExtra("data",new Gson().toJson(epcGoodsInfos));
//        intent.putExtra("warehouse",new Gson().toJson(inWarehouseBean));
        intent.putExtra("from","AllocationActivity");
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
